﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1400"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="收货单位" prop="store">
                        <sc-apply-org-select
                            ref="orgselect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="entityObj.store"
                            :multiple="false"
                            @fatherMethod="orgSelectProcess"
                            style="width: 100%;"
                        ></sc-apply-org-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="赠送单位" prop="purchaseUnityName">
                        <el-input v-model="entityObj.purchaseUnityName" disabled />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="赠送人" prop="giveName">
                        <el-input v-model="entityObj.giveName" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="赠送时间" prop="giveDate">
                        <el-date-picker
                            v-model="entityObj.giveDate"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请输入赠送时间"
                            style="width: 100%;margin-left: 9px;"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="附件上传">
                        <sc-upload-file
                            v-model="entityObj.fileUrlStr"
                            :objName="'Supply/giveOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="赠送清单:" prop>
                        <el-col :span="12">
                            <el-button size="small" @click="addMaterial()">添加物料</el-button>
                        </el-col>
                        <el-table
                            :data="entityObj.giveOrderItems"
                            border
                            style="width: 100%"
                            show-summary
                        >
                            <el-table-column label="操作" min-width="100" align="center">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        class="addbtnbg"
                                        @click="deleteRow(scope.row,scope.$index)"
                                    >删除</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料编码" min-width="110" prop="materialCode"></el-table-column>
                            <el-table-column label="物料名称" min-width="130" prop="materialName"></el-table-column>
                            <el-table-column label="分类" min-width="130" prop="materialTypeName"></el-table-column>
                            <el-table-column label="规格" min-width="140" prop="materialSpecs"></el-table-column>
                            <el-table-column label="单位" min-width="70" prop="unitName"></el-table-column>
                            <el-table-column label="供应商" min-width="140" align="center">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---供应商---"
                                        v-model="scope.row.supplier"
                                        style="width: 100%"
                                        @change="supplierHandleChange(scope.row,scope.row.supplier)"
                                    >
                                        <el-option
                                            v-for="item in scope.row.suppliers"
                                            :key="item.orgType+'_'+item.orgId"
                                            :label="item.orgName"
                                            :value="item.orgType+'_'+item.orgId"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="赠送模式" min-width="140" align="center">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---赠送模式---"
                                        v-model="scope.row.purchaseSaleType"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems"
                                            :key="item.purchaseSaleType"
                                            :label="item.purchaseSaleTypeDesc"
                                            :value="item.purchaseSaleType"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存" min-width="60" align="center">
                                <template
                                    #default="scope"
                                >{{scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.stockQty}}</template>
                            </el-table-column>
                            <el-table-column
                                label="销售单价"
                                width="150"
                                prop="applyPrice"
                                align="center"
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.purchaseSaleType<20"
                                    >{{scope.row.applyPrice=scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.applyPrice}}</span>
                                    <el-input-number
                                        v-else
                                        v-model="scope.row.applyPrice"
                                        :precision="0"
                                        :step="1"
                                        :disabled="false"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="采购单价" min-width="100" prop="price" align="center">
                               <template #default="scope" >{{scope.row.price=scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.price??0}}</template> 
                                <template
                                    #default="scope"
                                >{{scope.row.price=scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.price}}</template>
                            </el-table-column>-->
                            <el-table-column label="赠送数量" prop="qty" min-width="140">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        step="1"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="审核结果备注" prop="remarks" min-width="120">
                                <template #default="scope">
                                    <el-input
                                        v-model="scope.row.remarks"
                                        step="1"
                                        style="width: 100%"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注:">
                        <el-input
                            v-model="entityObj.remarks"
                            :rows="4"
                            type="textarea"
                            placeholder="赠送备注"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(0)"
            >暂 存</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(1)"
            >保 存</el-button>
        </template>

        <template>
            <el-dialog
                v-model="materialState"
                title="选择商品"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 500px"
            >
                <el-row style="margin-bottom: 40px;">
                    <sc-material-choice ref="scMaterialChoice" :queryType="'material/item-pages'"></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
    </full-screen-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                giveOrderItems: [],
            },
            materialState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                store: [{ required: true, type: "object", message: "请填写" }],
                giveName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                giveDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseUnityName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                giveOrderItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            storeProps: {
                label: "storeOrgName",
                value: "storeId",
            },
            warehouseProps: {
                label: "warehouseName",
                value: "warehouseId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            optionsCreateType: [],
            optionsSourceType: [],
            optionsInStockType: [],
            itemsData: [],
        };
    },
    computed: {},
    methods: {
        //显示=
        async open(mode = "Add") {
            this.mode = mode;
            this.visible = true;

            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "give-order/create"
                                    : "give-order/update",
                                { ...this.entityObj, status: status }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(row) {
            this.entityObj = { giveOrderItems: [] };
            if (row) {
                console.log(1111);
                try {
                    var returnValue = await this.$API.auth.GetProcessApi.get(
                        `give-order/${row.giveOrderId}`,
                        {}
                    );
                    if (returnValue.status == 200) {
                        const materialItemIds =
                            returnValue.response.giveOrderItems.map(
                                (p) => p.materialItemId
                            );

                        const returnValue1 =
                            await this.$API.auth.PostProcessApi.post(
                                "purchase-protocol/orgs",
                                {
                                    storeId: returnValue.response.storeId,
                                    orderType: 1,
                                    materialItemIds: materialItemIds,
                                }
                            );
                        if (returnValue1.status == 200) {
                            if (!this.suppliers) {
                                this.suppliers = [];
                            }
                            this.suppliers.push(...returnValue1.response);
                            returnValue.response.giveOrderItems.map((p) => {
                                const purchase = this.suppliers.find(
                                    (t) => t.materialItemId == p.materialItemId
                                );
                                //获取所有供应商
                                const suppliers = purchase.purchaseOrgs;
                                //默认供应商
                                const supplier =
                                    suppliers.find(
                                        (p) =>
                                            p.supplierId == purchase.supplierId
                                    ) ?? suppliers[0];
                                p.suppliers = suppliers;
                                p.supplier=p.supplierOrgType+"_"+p.supplierId
                            });

                            this.entityObj = {
                                ...returnValue.response,
                                store: {
                                    storeId: returnValue.response.storeId,
                                    storeName: returnValue.response.storeName,
                                },
                            };

                            console.log(this.entityObj.giveOrderItems);
                        }
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },
        async initOptions() {},
        addMaterial() {
            if (!this.entityObj.storeId || this.entityObj.storeId == 0) {
                this.$message.error("请先选择要赠送的门店");
                return;
            }
            this.materialState = true;
        },
        deleteRow(row, index) {
            this.entityObj.giveOrderItems.splice(index, 1);
        },
        async setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            const materialItemIds = materials.map((p) => p.materialItemId);
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "purchase-protocol/orgs",
                {
                    storeOrgType: this.entityObj.storeOrgType,
                    storeId: this.entityObj.storeId,
                    orderType: 1,
                    materialItemIds: materialItemIds,
                }
            );
            if (returnValue.status == 200) {
                if (!this.suppliers) {
                    this.suppliers = [];
                }
                this.suppliers.push(...returnValue.response);
                materials.map((p) => {
                    const suppliers = this.suppliers.find(
                        (t) => t.materialItemId == p.materialItemId
                    ).purchaseOrgs;
                    this.entityObj.giveOrderItems.push({
                        suppliers: suppliers,
                        supplierOrgType:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].orgType
                                : null,
                        supplierId:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].orgId
                                : null,
                        optionsPurchaseSaleType:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].purchaseSaleItems
                                : null,
                        purchaseSaleType:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].purchaseSaleItems[0]
                                      ?.purchaseSaleType
                                : null,
                        stockQty:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.stockQty
                                : null,
                        applyPrice:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.applyPrice
                                : 0,
                        price:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.price
                                : 0,
                        materialId: p.materialId,
                        materialCode: p.materialCode,
                        materialName: p.materialName,
                        materialSpecs: p.materialSpecs,
                        materialTypeId: p.materialTypeId,
                        materialTypeName: p.materialTypeName,
                        unitCode: p.unitCode,
                        unitName: p.unitName,
                        remarks: "同意",
                        materialItemId: p.materialItemId,
                    });
                });
            }

            console.log(this.entityObj.giveOrderItems);
            this.materialState = false;
        },
        async orgSelectProcess(rowData) {
            this.entityObj.store = rowData;
            this.entityObj.storeOrgType = rowData.storeOrgType;
            this.entityObj.storeId = rowData.storeId;
        },
        async supplierHandleChange(row,supplier) {
            const supplierVal= supplier.split('_')
            row.supplierOrgType = supplierVal[0];
            row.supplierId = supplierVal[1];
            console.log("supplierOrgType", row);
        },
    },
    async mounted() {
        this.entityObj = { giveOrderItems: [] };
        this.entityObj.purchaseUnityName = tool.data.get("USER_INFO").OrgName;
        this.entityObj.giveName = tool.data.get("USER_INFO").Name;
        this.entityObj.giveDate = tool.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style></style>
